import random
from media_handler import format_media_item_for_display


def view_my_library_interaction(all_media):
    """
    提供查看书单/影单的交互逻辑
    """
    print("请选择查看的内容：")
    print("1. 查看所有书单")
    print("2. 查看所有影单")
    print("3. 查看全部")
    choice = input("请输入选项（1/2/3）：")

    if choice == "1":
        filtered_media = [item for item in all_media if item.get("type") == "book"]
    elif choice == "2":
        filtered_media = [item for item in all_media if item.get("type") == "movie"]
    elif choice == "3":
        filtered_media = all_media
    else:
        print("无效的选项！")
        return

    if not filtered_media:
        print("暂无相关数据！")
        return

    print("\n查看结果：")
    for index, item in enumerate(filtered_media, start=1):  # 添加计数器 index，从1开始
        # 调用原函数获取带ID的显示字符串（如 "123. 解忧杂货店 (book) - 未开始"）
        original_display = format_media_item_for_display(item, display_type="summary")  # 保留参数名
        # 拆分字符串，去掉ID部分，替换为顺序编号
        title_part = original_display.split(". ", 1)[-1]  # 按第一个". "拆分，取后半部分
        print(f"{index}. {title_part}")  # 用index作为顺序编号


def filter_media_by_criteria(all_media, criteria_dict):
    filtered = all_media.copy()
    if 'genre' in criteria_dict:
        genre = criteria_dict['genre']
        filtered = [m for m in filtered if m.get('genre') == genre]

    if 'min_rating' in criteria_dict:
        min_rating = criteria_dict['min_rating']
        filtered = [m for m in filtered if m.get('rating') is not None and m['rating'] >= min_rating]

    if 'status' in criteria_dict:
        status = criteria_dict['status']
        filtered = [m for m in filtered if m.get('status') == status]

    if 'media_type' in criteria_dict:
        media_type = criteria_dict['media_type']
        filtered = [m for m in filtered if m.get('type') == media_type]

    return filtered


def search_media_by_keyword(all_media, keyword):
    keyword = keyword.lower()
    return [m for m in all_media
            if keyword in (m.get('title', '') or '').lower()
            or keyword in (m.get('author', '') or '').lower()
            or keyword in (m.get('director', '') or '').lower()
            or keyword in (m.get('review', '') or '').lower()]


def filter_or_search_interaction(all_media):
    print("\n=== 筛选/搜索菜单 ===")
    print("1. 按类型筛选")
    print("2. 按评分筛选")
    print("3. 按关键词搜索")
    choice = input("请选择操作 (1-3): ").strip()

    results = []

    if choice == '1':
        genre = input("请输入要筛选的类型 (如 小说, 科幻, 历史, 传记, 哲学, 经济, 计算机, 心理学, 其他): ").strip()
        criteria = {"genre": genre}
        results = filter_media_by_criteria(all_media, criteria)

    elif choice == '2':
        try:
            min_rating = float(input("请输入最低评分 (如 4.5): ").strip())
            criteria = {"min_rating": min_rating}
            results = filter_media_by_criteria(all_media, criteria)
        except ValueError:
            print("无效的评分值，请输入数字")
            return

    elif choice == '3':
        keyword = input("请输入搜索关键词: ").strip()
        results = search_media_by_keyword(all_media, keyword)

    else:
        print("无效的选择")
        return

    if results:
        print(f"\n找到 {len(results)} 个结果:")
        for index, item in enumerate(results, start=1):  # 添加计数器 index
            original_display = format_media_item_for_display(item, display_type="summary")  # 保留参数
            title_part = original_display.split(". ", 1)[-1]
            print(f"{index}. {title_part}")  # 用index替代原ID
    else:
        print("\n未找到匹配的媒体项")


def get_random_recommendation(all_media, media_type=None, based_on_genre=None):
    unread_media = [m for m in all_media if m.get('status') == '未开始']
    if media_type:
        unread_media = [m for m in unread_media if m.get('type') == media_type]

    if based_on_genre:
        unread_media = [m for m in unread_media if m.get('genre') == based_on_genre]

    return random.choice(unread_media) if unread_media else None


def recommend_media_interaction(all_media):
    print("\n=== 随机推荐 ===")
    print("1. 书籍推荐")
    print("2. 影视推荐")
    media_choice = input("请选择媒体类型 (1-2): ").strip()

    media_type = "book" if media_choice == '1' else "movie" if media_choice == '2' else None
    if not media_type:
        print("无效的选择")
        return

    use_genre = input("是否基于喜好类型推荐? (Y/N): ").strip().lower() == 'y'
    genre = None

    if use_genre:
        genre = input("请输入你喜欢的类型 (如 小说, 科幻, 历史, 传记, 哲学, 经济, 计算机, 心理学, 其他): ").strip()

    recommendation = get_random_recommendation(all_media, media_type, genre)

    if recommendation:
        print("\n为你推荐:")
        original_display = format_media_item_for_display(recommendation, display_type="summary")
        title_part = original_display.split(". ", 1)[-1]
        print(f"1. {title_part}")
    else:
        print("\n没有找到符合条件的推荐")